package com.weng.cloud.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: weng
 * @Date: 2022/3/13
 * @Description: com.weng.cloud.zuul.filter
 */
@Component
public class MyZuulFilter extends ZuulFilter {

    private final static String PREFIX_PARAM = "/testZuulFilter/";

    @Override
    public String filterType() {
        return "route";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        try {
            StringBuffer requestURL = request.getRequestURL();
            int bgnIndex = requestURL.indexOf(PREFIX_PARAM) + PREFIX_PARAM.length();
            //int endIndex = requestURL.toString().length();
            //String numbStr = request.getParameter("numb");
            String numbStr = requestURL.substring(bgnIndex);
            Integer numbInt = Integer.valueOf(numbStr);
            numbInt = 8 / numbInt;
            request.setAttribute("numb",numbInt);
            requestContext.setRequest(request);
        } catch (Exception e) {
            System.err.println("springcloud alibaba 好香甜");
            e.printStackTrace();
            requestContext.set("error.status_code",401);
            requestContext.set("error.exception",e);
            requestContext.set("error.message","怎么都是些打工游戏呀?");
        }
        return null;
    }
}
